import java.util.ArrayDeque;
import java.util.Deque;
import java.util.Stack;

/**
 *  1021. 删除最外层的括号;
 *
 *  输入：s = "(()())(())(()(()))"
 * 输出："()()()()(())"
 * 解释：
 * 输入字符串为 "(()())(())(()(()))"，原语化分解得到 "(()())" + "(())" + "(()(()))"，
 * 删除每个部分中的最外层括号后得到 "()()" + "()" + "()(())" = "()()()()(())"。
 */
public class Test {
    public static String removeOuterParentheses(String s) {
        StringBuffer bs = new StringBuffer();
        Deque<Character> stack = new ArrayDeque<>();
        for (int i = 0; i < s.length(); i++) {
            char c = s.charAt(i);
            if (c == ')') {
                stack.pop();
            }
            if (!stack.isEmpty()) {
                bs.append(c);
            }
            if (c == '(') {
                stack.push(c);
            }
        }
        return bs.toString();
    }


    public static void main(String[] args) {
        System.out.println(removeOuterParentheses("(((())))"));
    }
}
